import { setColumns } from './setColumns';
import { setMainTableClick, setAttrs, setRequestApi } from './setOther';
import { setButton } from './setTableButton';
/**设置表格数据默认值 */
export const setTableData = async (json, configPageParams) => {
  const { ref } = json.useDataGrid || {};
  if (!ref) {
    elMessage('表格ref必须配置', 'error');
    return;
  }

  let tableData = {
    ref
  };
  // 设置表格属性
  const attrs = setAttrs(json.useDataGrid, tableData);
  Object.assign(tableData, { tableAttrs: attrs });

  // 设置表格列相关
  await setColumns(json.useDataGrid, tableData, configPageParams);

  // 设置表格请求相关配置
  setRequestApi(json.useDataGrid, tableData, configPageParams);

  // 设置按钮相关
  setButton(json.useDataGrid, tableData, configPageParams);

  // 设置页面引入组件
  const comp = json?.configForm?.form?.components;
  if (comp) {
    const comps = JSON.parse(comp);
    console.log(comps, 'comps');
    if (comps.length) {
      configPageParams.comps.push(...comps);
    }
  }

  return tableData;
};

/**设置明细 */
export const setDetailTableData = async (detailList, configPageParams, mainData) => {
  if (!detailList || !detailList.length) {
    return;
  }

  const detailsTableData = {
    visible: true,
    activeName: JSON.parse(detailList[0].json).useDataGrid.ref,
    details: []
  };

  for (let item of detailList) {
    const js = JSON.parse(item.json);
    item = await setTableData(js, configPageParams);
    setMainTableClick(js.useDataGrid, item, mainData, configPageParams);
    detailsTableData.details.push(item);
  }

  mainData.detailsTableData = detailsTableData;
};

/**设置弹框表格 */

export async function setDialogTableData(dialogData, configPageParams, mainData) {
  if (!dialogData || !dialogData.length) {
    return;
  }

  const dialogTable = {
    details: []
  };

  for (let item of dialogData) {
    const js = JSON.parse(item.json);

    item = await setTableData(js, configPageParams);
    // 用于显示隐藏弹框
    item.visible = false;
    // 设置弹框全局属性
    const attrs = setAttrs(js.useDataGrid, item, 'dialogAttrs-');
    Object.assign(item, { dialogAttrs: attrs });
    dialogTable.details.push(item);
  }

  console.log(dialogTable, 'dialogTable');

  mainData.dialogTable = dialogTable;
}
